package research.sbookmarking.io;

import java.io.*;
import java.util.*;

public class InputStreamFactory {

	private static InputStreamFactory anInstance = null;
	private HashMap<String,Object> filestreamCache = new HashMap<String,Object>();
	
	protected InputStreamFactory () {
		
	}

	protected InputStream getInputStream(String filename) {
		InputStream stream = null;
		
		stream = (InputStream)getStream(filename);
		if (stream == null){
			stream = openInputStream (filename);
			filestreamCache.put(filename,stream);
		}
		return stream;
	}
	
	protected InputStream openInputStream (String filename){
		try {
			return new FileInputStream(filename);
		}
		catch (IOException e){
			throw new RuntimeException(e);
		}
	}
	
	public Object getStream(String filename){
		return filestreamCache.get(filename);
	}
	
	public  BufferedReader getFileReader (String filename) {
		BufferedReader stream = null;
		
		try {
			stream = (BufferedReader)getStream(filename);
			if (stream == null){
				InputStreamReader in = new InputStreamReader (getInputStream(filename),"UTF-8");
				stream = new BufferedReader (in);
				filestreamCache.put(filename,stream);
			}
			return stream;
		}
		catch (IOException e){
			throw new RuntimeException(e);
		}
	}

	public void removeStream (String filename){
		filestreamCache.remove(filename);
	}
		
	public static InputStreamFactory getInstance(){
		if (anInstance == null){
			anInstance = new InputStreamFactory();
		}
		return anInstance;
	}
}
